<?php
 include_once("connect.inc.php");
 
function addItem($channelId,$title,$link,$description,$guid,$author){
	
	global $db;
	
	$sql = "LOCK TABLES item WRITE";
	$db->sql_query($sql);
	
	$sql="INSERT INTO item ";
	$add['channelId'] = $channelId;
	$add['title']=$title;
	$add['link']=$link;
	$add['description']=removeTag(unescape($description));
	// $add['pubdate']=$pubdate;
	$add['guid']=$guid;
	$add['author']=$author;
	$col="";
	$val="";
	foreach($add as $key => $value){
		$value=trim($value);
		if($value!=""){
			$col=$col."$key,";
			$val=$val."'$value',";
		}
	}
	if($col!=""){
		$col=" (".substr($col,0,strlen($col)-1).",pubdate,real_pubDate".") ";
		$val=" VALUE(".substr($val,0,strlen($val)-1).",NOW(),NOW()".") ";
		$sql=$sql.$col.$val;
		$query = $db->sql_query($sql);  //] this two line must be together
		$id = mysql_insert_id();		//]	this two line must be together
		$sql = "UNLOCK TABLES";
		$db->sql_query($sql);
		return $id;		

	}
	
	$sql = "UNLOCK TABLES";
	$db->sql_query($sql);
	
	return false;
}
/**
 * Edit the existing item in database.
 * Return true if editing successes.
 */
function editItem($item_id,$channelId,$title,$link,$description,$guid,$author) {
	global $db;
	
	$sql = "LOCK TABLES item WRITE";
	$db->sql_query($sql);
	$sql = "UPDATE item SET ";
	$add['channelId'] = $channelId;
	$add['title']=$title;
	$add['link']=$link;
	$add['description']=removeTag(unescape($description));
	$add['guid']=$guid;
	$add['author']=$author;
	$set="";
	foreach($add as $key => $value){
		$value=trim($value);
		if($value!=""){
			$set=$set." $key='$value',";
		}
	}
	
	if($set!=""){
		$set=substr($set,0,strlen($set)-1);
		$sql=$sql.$set." WHERE id=$item_id";
		//echo $sql;
		$db->sql_query($sql);
	}
	
	$sql = "UNLOCK TABLES";
	$db->sql_query($sql);
}
// /**
 // * Remove the existing item in database.
 // * Return true if removing successes or the item to be removed not found.
 // */
function removeItem($item_id) {
	global $db;
	
	$sql = "LOCK TABLES file WRITE, item WRITE";
	$db->sql_query($sql);
	
	$sql = "DELETE FROM item WHERE id = '" . $item_id . "'";
	$db->sql_query($sql);
	$sql = "DELETE FROM file WHERE itemid = '" . $item_id . "'";
	$db->sql_query($sql);
	
	$sql = "UNLOCK TABLES";
	$db->sql_query($sql);
}
// /**
 // * Show the new item that is recently added.
 // * Return the array of the new item.
 // */
function show_item($item_id) {
	global $db;
	
	$sql = "SELECT * FROM item WHERE id = '" . $item_id . "'";
	$query = $db->sql_query($sql);
	
	return $db->sql_fetchrow($query);
}
// /**
 // * Search the items adder want to view.
 // * Return array of item's id, or null if no item found.
 // */
function search_item($keyword, $field = "") {
	global $db;
	
	if($field == "") {
		$sql = "SELECT * FROM item WHERE 
				LOWER(title) LIKE LOWER('%" . $keyword . "%') 
				OR LOWER(link) LIKE LOWER('%" . $keyword . "%') 
				OR LOWER(description) LIKE LOWER('%" . $keyword . "%') 
				OR LOWER(author) LIKE LOWER('%" . $keyword . "%')";
	} else {
		$sql = "SELECT * FROM item WHERE LOWER(" . $field . ") LIKE LOWER('%" . $keyword . "%')";
	}
	
	$query = $db->sql_query($sql);
	
	while($row = $db->sql_fetchrow($query)) {
		$result[] = $row;
	}
	
	return $result;
}
function showFileById($fileId){
	global $db;
	$sql = "SELECT * FROM file WHERE id = '" . $fileId . "'";
	$query = $db->sql_query($sql);
	return $db->sql_fetchrow($query);
}
function getAllNotPublish($providerUsername){
	global $db;
	$sql="SELECT * FROM item where isPublish=0 
		and author='$providerUsername' ORDER BY item.pubdate DESC ";
	//echo $sql;
	$result=$db->sql_query($sql);
	return $db->sql_fetchrowset($result);
}
/**
 * Return the current time in format "YYYY-MM-DD hh:mm:ss".
 */
function get_current_time() {
	return date("Y-m-d H:i:s");
}
// /**
 // * Return the id of the new item that is recently added.
 // */
// function get_latest_id($title, $url, $description, $date) {
	// global $db;
	
	// $sql = "SELECT id FROM item WHERE 
			// title = '" . $title . "' 
			// AND link = '" . $url . "' 
			// AND description = '" . $description . "' 
			// AND pubdate = '" . $date . "'";
	// $query = $db->sql_query($sql);
	
	// $row = $db->sql_fetchrow($query);
	
	// return $row[0];
// }
	
function getAvailableChannel($username){
	global $db;
	$sql = 'SELECT * FROM channel RIGHT JOIN (SELECT * FROM providerchannel WHERE
			  username="'.$username.'") AS tempuserchannel
			  ON channel.id = tempuserchannel.channelid';
	//echo $sql;
	$query = $db->sql_query($sql);
	return $db->sql_fetchrowset($query);
}
function lastModified(){
	global $db;
	$sql = "show table status where name='item'";
	$query = $db->sql_query($sql);
	$result = $db->sql_fetchrow($query);
	return $result['Update_time']."/".$result['Rows'];
}
/**
 * Function converts an Javascript escaped string back into a string with specified charset (default is UTF-8). 
 * Modified function from http://pure-essence.net/stuff/code/utf8RawUrlDecode.phps
 *
 * @param string $source escaped with Javascript's escape() function
 * @param string $iconv_to destination character set will be used as second paramether in the iconv function. Default is UTF-8.
 * @return string 
 */
function unescape($source, $iconv_to = 'UTF-8') {
  $decodedStr = '';
  $pos = 0;
  $len = strlen ($source);
  while ($pos < $len) {
      $charAt = substr ($source, $pos, 1);
      if ($charAt == '%') {
          $pos++;
          $charAt = substr ($source, $pos, 1);
          if ($charAt == 'u') {
              // we got a unicode character
              $pos++;
              $unicodeHexVal = substr ($source, $pos, 4);
              $unicode = hexdec ($unicodeHexVal);
              $decodedStr .= code2utf($unicode);
              $pos += 4;
          }
          else {
              //we have an escaped ascii character
              $hexVal = substr ($source, $pos, 2);
              $decodedStr .= chr (hexdec ($hexVal));
              $pos += 2;
          }
      }
      else {
          $decodedStr .= $charAt;
          $pos++;
      }
  }
  if ($iconv_to != "UTF-8") {
      $decodedStr = iconv("UTF-8", $iconv_to, $decodedStr);
  }
  
  return $decodedStr;
}
/**
 * Function coverts number of utf char into that character.
 * Function taken from: http://sk2.php.net/manual/en/function.utf8-encode.php#49336
 *
 * @param int $num
 * @return utf8char
 */
function code2utf($num){
  if($num<128)return chr($num);
  if($num<2048)return chr(($num>>6)+192).chr(($num&63)+128);
  if($num<65536)return chr(($num>>12)+224).chr((($num>>6)&63)+128).chr(($num&63)+128);
  if($num<2097152)return chr(($num>>18)+240).chr((($num>>12)&63)+128).chr((($num>>6)&63)+128) .chr(($num&63)+128);
  return '';
}
function removeTag($sSource) {
	$aAllowedTags = array('<a>', '<b>', '<big>', '<blockquote>', '<br>', '<caption>', '<center>', '<cite>', '<code>', '<dd>', '<div>', '<dl>', '<dt>', '<em>', '<font>', '<h1>', '<h2>', '<h3>', '<h4>', '<h5>', '<h6>', '<hr>', '<i>', '<img>', '<li>', '<ol>', '<p>', '<pre>', '<s>', '<small>', '<strike>', '<strong>', '<sub>', '<sup>', '<table>', '<td>', '<th>', '<tr>', '<tt>', '<u>', '<ul>', '<var>');
	$aDisabledAttributes = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavaible', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragdrop', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterupdate', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmoveout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
	return preg_replace('/\s(' . implode('|', $aDisabledAttributes) . ').*?([\s\>])/', '\\2', preg_replace('/<(.*?)>/ie', "'<' . preg_replace(array('/javascript:[^\"\']*/i', '/(" . implode('|', $aDisabledAttributes) . ")[ \\t\\n]*=[ \\t\\n]*[\"\'][^\"\']*[\"\']/i', '/\s+/'), array('', '', ' '), stripslashes('\\1')) . '>'", strip_tags($sSource, implode('', $aAllowedTags))) );
    }
?>